var express = require('express');
var router = express.Router();
var path = require('path');
var async  = require( 'async'); // 同步控制
var redis = require("redis");
var Scripto = require('redis-scripto');
var CONFIG = require('../../../../common/config');




var redisManager = (function () {
    function redisManager() {
    }

    /**
     * 初始化 redis 的脚本管理器
     *
     * @author mk
     * @date 2018-5-30
     */
    redisManager.setupRedisClients = function () {
        // 如果初始化过就不再初始化
        if(redisManager.scriptManagers) {
            return;
        }
        //----------------- openApi相关redis配置-----------------------
        redisManager.scriptManagers = {};
        var luaPath = path.resolve(__dirname, '../script/lua/data_statistics');
        var client = redis.createClient({
            host:CONFIG.YJX_DATA_STATISTICS_REDIS_DOMAIN,
            auth_pass:CONFIG.YJX_DATA_STATISTICS_REDIS_PASSWORD,
            port:CONFIG.YJX_DATA_STATISTICS_REDIS_PORT,
            db:CONFIG.YJX_DATA_STATISTICS_REDIS_DB_NUMBER,
            ttl:CONFIG.YJX_DATA_STATISTICS_REDIS_TTL
        });
        var mgrCache = new Scripto(client);
        mgrCache.loadFromDir(luaPath);
        // 记录配置 manager
        redisManager.scriptManagers.cache = mgrCache;
    };


    /**
     * 获取redis 的配置管理db 的脚本管理器
     *
     * @author mk
     * @date 2018-5-30
     *
     * @param callback 回调
     *             err: 获取失败
     *             scriptManager: 获取到的配置db 的脚本管理器
     */
    redisManager.getApiRedisDBMgr = function (callback) {
        if(!redisManager.scriptManagers.cache) {
            return callback('redis search config 尚未初始化');
        }
        return callback(null, redisManager.scriptManagers.cache);
    };


    //------------------------------------------------------------------
    return redisManager;
})();

// 初始化 redis clients
redisManager.setupRedisClients();




//------------------------------------------------------------------
module.exports = redisManager;

